<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    // 输入：nums = [-1,2,1,-4], target = 1
    // 输出：2
    // 解释：与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。

    // 输入：nums = [0,0,0], target = 1 
    // 输出：0
    /**
     * 循环加 双指针
     */
    console.log(threeSumClosest([4, 0, 5, -5, 3, 3, 0, -4, -5], -2));
    function threeSumClosest(nums, target) {
        let resNum = nums[0] + nums[1] + nums[2];
        let len = nums.length - 1;
        let arr = nums.sort((a, b) => a - b)
        for (let i = 0; i < len; i++) {
            let L = i + 1
            let R = len
            if (i == len - 1) continue;
            while (L < R) {
                let sum = arr[i] + arr[L] + arr[R]
                let resABS = Math.abs(target - resNum)
                let sumABS = Math.abs(target - sum)
                //比较每次移动后 的 差值 
                if (sumABS < resABS) resNum = sum
                //每次移动后的值 大于tar 右指针移动  反之 做指针移动
                if (sum > target) R--
                else L++
            }

        }
        return resNum
    };

</script>

</html>